<script>
import { defineComponent, ref, reactive, onUnmounted } from "vue";
import { Cropper } from "vue-advanced-cropper";
import "vue-advanced-cropper/dist/style.css";

export default defineComponent({
  components: {
    Cropper
  },
  setup() {
    const image = reactive({
      src: "https://images.unsplash.com/photo-1619737307100-55b82496fcda?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80",
      type: "image/jpg",
    })

    const cropper = ref()
    const file = ref()

    const cropImage = () => {
      if (cropper.value) {
        const {canvas} = cropper.value.getResult()
        const newTab = window.open()
        if (newTab && canvas) {
          newTab.document.body.innerHTML = `<img src="${canvas.toDataURL(image.type)}"></<img>`
        }
      }
    }

    const uploadImage = (event) => {
      /// Reference to the DOM input element
      const { files } = event.target;
      // Ensure that you have a file before attempting to read it
      if (files && files[0]) {
        // 1. Revoke the object URL, to allow the garbage collector to destroy the uploaded before file
        if (image.src) {
          URL.revokeObjectURL(image.src);
        }
        // 2. Create the blob link to the file to optimize performance:
        const blob = URL.createObjectURL(files[0]);

        // 3. Update the image. The type will be derived from the extension and it can lead to an incorrect result:
        image.src = blob;
        image.type = files[0].type;
      }
    }

    onUnmounted(()=>{
      if (image.src) {
        URL.revokeObjectURL(image.src)
      }
    })

    return {
      image,
      cropper,
      file,
      uploadImage,
      cropImage,
    }
  }
})
</script>

<template>
  <cropper ref="cropper" class="cropper" @change="change" :src="image.src" />
  <div class="button-wrapper">
    <button class="button" @click="file.click()">
      <input
          type="file"
          ref="file"
          @change="uploadImage($event)"
          accept="image/*"
      />
      Upload image
    </button>
    <button class="button" @click="cropImage()">Crop image</button>
  </div>
</template>

<style scoped lang="scss">
.cropper {
  max-height: 500px;
}

.button-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 17px;
}

.button {
  color: white;
  font-size: 16px;
  padding: 10px 20px;
  width: 100%;
  background: #151515;
  cursor: pointer;
  transition: background 0.5s;
  border: none;
  &:not(:last-of-type) {
    margin-right: 10px;
  }
  &:hover {
    background: #2F2F2F;
  }
  input {
    display: none;
  }
}
</style>